<template>
  <div class="device-owner-layout">
    <AppSidebar
      :active-menu="activeMenu"
      ref="sidebarRef"
    >
      <template #menu-items>
        <el-menu-item index="/device-owner/dashboard">
          <el-icon><Monitor /></el-icon>
          <template #title>控制台</template>
        </el-menu-item>
        
        <el-menu-item index="/device-owner/devices">
          <el-icon><VideoPlay /></el-icon>
          <template #title>我的设备</template>
        </el-menu-item>
                
        <el-menu-item index="/device-owner/advertisements">
          <el-icon><Picture /></el-icon>
          <template #title>广告市场</template>
        </el-menu-item>

        <el-menu-item index="/device-owner/negotiations">
          <el-icon><ChatDotRound /></el-icon>
          <template #title>协商管理</template>
        </el-menu-item>
        
        <el-menu-item index="/device-owner/schedule-management">
          <el-icon><Calendar /></el-icon>
          <template #title>排期状态管理</template>
        </el-menu-item>

        <el-menu-item index="/device-owner/income">
          <el-icon><Money /></el-icon>
          <template #title>收入管理</template>
        </el-menu-item>



        <!-- <el-menu-item index="/device-owner/settings">
          <el-icon><Setting /></el-icon>
          <template #title>账户设置</template>
        </el-menu-item> -->
        
        <!-- 添加消息通知菜单项 -->
        <el-menu-item index="/device-owner/notification">
          <el-icon><Bell /></el-icon>
          <template #title>
            消息通知
          </template>
        </el-menu-item>
      </template>
    </AppSidebar>
    
    <div class="main-content" :class="{ 'expanded': sidebarRef?.isCollapsed }">
      <AppHeader
        :username="username"
        :user-avatar="userAvatar"
        :notification-count="notificationCount"
        @logout="handleLogout"
        @profile="handleProfile"
        @view-notifications="navigateToNotifications"
      />
      
      <div class="content">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <keep-alive :include="cachedViews">
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox } from 'element-plus';
import { 
  Monitor, VideoPlay, ChatDotRound, Money, Picture, Setting, Bell
} from '@element-plus/icons-vue';
import AppSidebar from '@/components/AppSidebar.vue';
import AppHeader from '@/components/AppHeader.vue';
import { useUserStore } from '@/stores/user';
import { getUnreadCount } from '@/api/notification';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const sidebarRef = ref(null);
let pollingTimer = null;

const username = computed(() => userStore.getUserInfo2().username || '未登录');
const userAvatar = computed(() => userStore.getUserInfo2().avatar || '');
const notificationCount = ref(0);
const activeMenu = computed(() => route.path);
const cachedViews = ref(['DeviceOwnerDashboard']);

// 获取未读消息数量
const fetchUnreadCount = async () => {
  try {
    const res = await getUnreadCount();
    if (res.data.code === 200) {
      notificationCount.value = res.data.data || 0;
    }
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
  }
};

// 开始轮询未读消息数量
const startPolling = () => {
  // 立即执行一次
  fetchUnreadCount();
  
  // 设置轮询，每分钟检查一次
  pollingTimer = setInterval(fetchUnreadCount, 60000);
};

// 导航到消息通知页面
const navigateToNotifications = () => {
  console.log('跳转到消息通知页面');
  router.push('/device-owner/notification');
};

const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.clearToken();
    userStore.clearUserInfo();
    router.push('/login');
  }).catch(() => {});
};

const handleProfile = () => {
  router.push('/userinfo');
};

onMounted(() => {
  // 启动消息轮询
  startPolling();
});

onBeforeUnmount(() => {
  // 清除轮询定时器
  if (pollingTimer) {
    clearInterval(pollingTimer);
  }
});
</script>

<style scoped>
.device-owner-layout {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: margin-left 0.3s;
}

.main-content.expanded {
  margin-left: -156px;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f0f2f5;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 通知徽章样式 */
.notification-badge {
  margin-left: 8px;
}

:deep(.el-menu--collapse) .notification-badge {
  position: absolute;
  right: 8px;
  top: 15px;
}
</style>